package com.bigchun.woodhunter;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.share.Sharer;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.widget.ShareDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import adapter.HorImageAdapter;
import bean.ContentDataBean;
import bean.GuigeDataBean;
import myapp.MyApp;
import myview.CustomProgressDialog;
import myview.HorizontalListView;
import util.DensityUtil;
import util.GlideUtils;
import util.MyLog;
import util.OrderEventMessage;
import util.PreferenceUtil;
import util.RequestManager;
import util.ShareUtil;
import util.SystemStatusManager;
import util.ZoomImageview;
import util.utils;

public class GoodsInfomationActivity extends BaseActivity {


    private Context context;
    private MyApp myapp;
    private LayoutInflater mInflater;
    private String goodsid;
    private int width;
    private int heightPixels;
    private String token;
    private ImageView img_bigimg;
    private LinearLayout ll_reback;
    private LinearLayout ll_fu;
    private HorizontalListView horlistview;
    private List<String> imglist = new ArrayList<>();
    private HorImageAdapter imgadapter;
    private String imagebig;
    private TextView tv_name;
    private TextView tv_price;
    private String store_name;
    private String store_info;
    private String price;
    private ImageView img_collect;
    private ImageView img_share;
    private String status;
    private String msgstr;
    private String collection = "0";
    private CallbackManager callbackManager;
    private ShareDialog shareDialog;
    private PopupWindow mPopupWindow;
    private String urlstr;
    private String domain;
    private Bitmap thumb = null;
    private String apptype = "";
    private String textData;
    private ContentDataBean.DataBean textContent;
    private LinearLayout ll_guige;
    private List<GuigeDataBean> guigelists = new ArrayList<>();
    private SharedPreferences sharedPreferences;
    private TextView tv_guige;
    private CustomProgressDialog customProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_goodsinfomation);
        context = this;
        myapp = (MyApp) getApplicationContext();
//        hideBottomUIMenu();
        EventBus.getDefault().register(this);
        sharedPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        apptype = sharedPreferences.getString("apptype", "0");
        domain = sharedPreferences.getString("domain", "");
        urlstr = sharedPreferences.getString("urlstr", "");
        textData = sharedPreferences.getString("textData", "");
        mInflater = LayoutInflater.from(context);
        goodsid = getIntent().getStringExtra("goodsid");
        MyLog.e("1111111111", "111111111 " + goodsid);
        textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {
        }.getType());

        FacebookSdk.sdkInitialize(this.getApplicationContext());
        callbackManager = CallbackManager.Factory.create();
        shareDialog = new ShareDialog(this);
        shareDialog.registerCallback(callbackManager, shareCallback);

        customProgressDialog = new CustomProgressDialog(context, "", R.style.CommProgressDialog);
        WindowManager.LayoutParams params = customProgressDialog.getWindow().getAttributes();
        params.alpha = 0.7f;//取值为0-1之间  0是全透明，1是不透明
        params.dimAmount=0f;   //取值为0-1之间  1是全黑
//		params.width = 180;//设置进度条的宽度
//		params.height = 180;//设置进度条的宽度
        customProgressDialog.getWindow().setAttributes(params);

        setTranslucentStatus();
        getScreenDen();
        initView();
        initData();
        initLin();
        getData();

    }

    @Subscribe
    public void onEventMainThread(OrderEventMessage event) {
        String message = event.getMessage();
        Log.e("message--new--order", message);
        if ("图片双击事件".equals(message)) {
            //TODO   显示大图
            String type = event.getType();
            Log.e("eventbus接收数据成功", type + "     ------");
            GlideUtils.loadImagedefault(context, imglist.get(Integer.parseInt(type))+"?x-oss-process=image/resize,w_420", img_bigimg);
//            showBigImage(type);
            ArrayList<String> ss = new ArrayList<>();
            for (int m = 0;m<imglist.size();m++){
                ss.add(imglist.get(m));
            }

            Intent intent = new Intent(context, ImageActivity.class);
            intent.putExtra("position",type);
            intent.putExtra("imgs",ss);
            context.startActivity(intent);
        }else if ("图片长按事件".equals(message)){
            String type = event.getType();
            String s = imglist.get(Integer.parseInt(type));
//            saveImagUtil.showDiaLog(context,s,textContent);
        }

    }

    private void initView() {
        tv_guige = findViewById(R.id.tv_guige);
        ll_reback = findViewById(R.id.ll_reback);
        ll_fu = findViewById(R.id.ll_fu);
        img_bigimg = findViewById(R.id.img_bigimg);
        horlistview = findViewById(R.id.horlistview);
        tv_name = findViewById(R.id.tv_name);
        tv_price = findViewById(R.id.tv_price);
        img_collect = findViewById(R.id.img_collect);
        img_share = findViewById(R.id.img_share);
        ll_guige = findViewById(R.id.ll_guige);
        imgadapter = new HorImageAdapter(context, imglist);
        horlistview.setAdapter(imgadapter);

        final ContentDataBean.DataBean textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {
        }.getType());
        if (textContent != null) {
            tv_guige.setText(textContent.getSpecification());
        }


        /*img_bigimg.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                String s = imglist.get(itemplag);
                saveImagUtil.showDiaLog(context,s,textContent);
                return true;
            }
        });*/

    }

    private void initData() {

    }

    private String imgUrl = "";
    private int itemplag = 0;
    @SuppressLint("ClickableViewAccessibility")
    private void initLin() {
        horlistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                imgUrl = imglist.get(i);
//                showBigImage(imgUrl);
                itemplag = i;
                GlideUtils.loadImagedefault(context, imglist.get(i)+"?x-oss-process=image/resize,w_420", img_bigimg);

                /*ArrayList<String> ss = new ArrayList<>();
                for (int m = 0;m<imglist.size();m++){
                    ss.add(imglist.get(m));
                }

                Intent intent = new Intent(context, ImageActivity.class);
                intent.putExtra("position",i);
                intent.putExtra("imgs",ss);
                context.startActivity(intent);*/

            }
        });
        img_collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("0".equals(collection)) {
                    //未收藏
                    //点击请求收藏接口
                    customProgressDialog.show();
                    getCollectData("0");
                } else if ("1".equals(collection)) {
                    //已收藏
                    //点击取消收藏接口
                    customProgressDialog.show();
                    getCollectData("1");
                }
            }
        });
        img_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popbyshare();
            }
        });
        ll_reback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        img_bigimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                showBigImage(imgUrl);
                ArrayList<String> ss = new ArrayList<>();
                for (int m = 0;m<imglist.size();m++){
                    ss.add(imglist.get(m));
                }

                Intent intent = new Intent(context, ImageActivity.class);
                intent.putExtra("position",itemplag+"");
                intent.putExtra("imgs",ss);
                context.startActivity(intent);


            }
        });
        /*img_bigimg.setOnTouchListener(new View.OnTouchListener() {
            int count = 0;
            int firClick = 0;
            int secClick = 0;

            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (MotionEvent.ACTION_DOWN == motionEvent.getAction()) {
                    count++;
                    if (count == 1) {
                        firClick = (int) System.currentTimeMillis();

                    } else if (count == 2) {
                        secClick = (int) System.currentTimeMillis();
                        if (secClick - firClick < 500) {
                            //双击事件
                            showBigImage(imgUrl);
                        }
                        count = 0;
                        firClick = 0;
                        secClick = 0;
                    }
                }
                return true;

            }
        });*/
    }

    /**
     * 请求商品详情
     */
    private void getData() {
        imglist.clear();
        guigelists.clear();
        String url = myapp.getWebConfig() + "/api/index/product_detail";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("product_id", goodsid);
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");
                    imagebig = data.getString("image");
                    JSONArray slider_image = data.getJSONArray("slider_image");
                    for (int i = 0; i < slider_image.length(); i++) {
                        imglist.add(slider_image.getString(i));
                    }
                    store_name = data.getString("store_name");
                    store_info = data.getString("store_info");
                    price = data.getString("price");
                    collection = data.getString("collection");
                    JSONArray attr = data.getJSONArray("attr");
                    for (int i = 0; i < attr.length(); i++) {
                        GuigeDataBean bean = new GuigeDataBean();
                        bean.setName(attr.getJSONObject(i).getString("attr_name"));
                        bean.setValue(attr.getJSONObject(i).getString("attr_value"));
                        guigelists.add(bean);
                    }

                    msg.arg1 = 4;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    /**
     * 收藏
     */
    private void getCollectData(String type) {
        String url = myapp.getWebConfig() + "/api/index/product_collection";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("product_id", goodsid);
        paramsMap.put("type", type);
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    msgstr = jsonObject.getString("msg");
                    JSONObject data = jsonObject.getJSONObject("data");
                    status = data.getString("status");


                    msg.arg1 = 3;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    @SuppressLint("HandlerLeak")
    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    String str = (String) msg.obj;
                    Toast.makeText(context, str, Toast.LENGTH_LONG).show();
                    break;
                case 1:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    if (textContent != null) {
                        Toast.makeText(context, textContent.getNet_error(), Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(context, getString(R.string.net_error), Toast.LENGTH_LONG).show();
                    }
                    break;
                case 2:
                    break;
                case 3:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    collection = status;
                    Toast.makeText(context, msgstr, Toast.LENGTH_LONG).show();
                    //收藏
                    if ("0".equals(status)) {
                        img_collect.setImageResource(R.mipmap.icon_collect_star);
                    } else if ("1".equals(status)) {
                        img_collect.setImageResource(R.mipmap.icon_collect_star_select);
                    }

                    break;
                case 4:
                    returnBitMap(imagebig);
                    if (imglist.size() > 0) {
                        imgUrl = imglist.get(0);
                        GlideUtils.loadImagedefault(getApplicationContext(), imglist.get(0)+"?x-oss-process=image/resize,w_420", img_bigimg);
                    }
                    imgadapter.setData(imglist,textContent);
                    tv_name.setText(store_name);
                    if (!"".equals(price)) {
                        tv_price.setText("￥" + price);
                        tv_price.setVisibility(View.VISIBLE);
                    } else {
                        tv_price.setVisibility(View.GONE);
                    }
                    if ("0".equals(collection)) {
                        //未收藏
                        img_collect.setImageResource(R.mipmap.icon_collect_star);
                    } else if ("1".equals(collection)) {
                        //已收藏
                        img_collect.setImageResource(R.mipmap.icon_collect_star_select);
                    }

                    for (int i = 0; i < guigelists.size(); i++) {
                        View view = View.inflate(context, R.layout.item_guige, null);
                        TextView tv_name = view.findViewById(R.id.tv_name);
                        TextView tv_value = view.findViewById(R.id.tv_value);
                        tv_name.setText(guigelists.get(i).getName() + "："+guigelists.get(i).getValue());
//                        tv_value.setText(guigelists.get(i).getValue());
                        ll_guige.addView(view);

                    }


                    break;
                case 11:
                    if (!islogin) {
                        islogin = true;
                        sharedPreferences.edit().putString("token", "").commit();
                        Intent intent = new Intent(context, LoginActivity.class);
                        context.startActivity(intent);
                        myapp.destoryActivity("主页面");
                    }
                    break;
            }
        }
    };
    private boolean islogin = false;

    /**
     * 设置状态栏背景状态
     */
    public void setTranslucentStatus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window win = getWindow();
            WindowManager.LayoutParams winParams = win.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            winParams.flags |= bits;
            win.setAttributes(winParams);
        }
        SystemStatusManager tintManager = new SystemStatusManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(0);//状态栏无背景
    }

    /**
     * 获取屏幕宽度
     */
    private void getScreenDen() {

        WindowManager manager = getWindowManager();
        DisplayMetrics dm = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(dm);
        //以要素为单位
        width = dm.widthPixels;
        heightPixels = dm.heightPixels;
        MyLog.e("获取屏幕高度", heightPixels + "    高度");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }

    private FacebookCallback<Sharer.Result> shareCallback = new FacebookCallback<Sharer.Result>() {
        @Override
        public void onCancel() {
            Log.e("Facebook", "Canceled");
            if (textContent != null) {
                Toast.makeText(context, textContent.getShare_cancle(), Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(context, getString(R.string.share_cancle), Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onError(FacebookException error) {
            Log.e("Facebook", String.format("Error: %s", error.toString()));
            if (textContent != null) {
                Toast.makeText(context, textContent.getShare_error(), Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(context, getString(R.string.share_error), Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onSuccess(Sharer.Result result) {
            Log.e("HelloFacebook", "Success!");
            if (textContent != null) {
                Toast.makeText(context, textContent.getShare_success(), Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(context, getString(R.string.share_success), Toast.LENGTH_LONG).show();
            }
            if (mPopupWindow != null) {
                mPopupWindow.dismiss();
            }
        }
    };

    /**
     * 弹出单个筛选框
     */
    private void popbyshare() {
        LayoutInflater layoutInflater = LayoutInflater.from(context);
        View popupWindow = layoutInflater.inflate(R.layout.popup_share, null);
        View viewById = popupWindow.findViewById(R.id.view_zhezhao);
        LinearLayout llwx = popupWindow.findViewById(R.id.llwx);
        LinearLayout llwxp = popupWindow.findViewById(R.id.llwxp);
        LinearLayout llfacebook = popupWindow.findViewById(R.id.llfacebook);
        TextView tv_cancle_share = popupWindow.findViewById(R.id.tv_cancle_share);
        TextView tv_wx = popupWindow.findViewById(R.id.tv_wx);
        TextView tv_wxp = popupWindow.findViewById(R.id.tv_wxp);

        ContentDataBean.DataBean textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {
        }.getType());
        if (textContent != null) {
            tv_wx.setText(textContent.getWx_friend());
            tv_wxp.setText(textContent.getQuan());
            tv_cancle_share.setText(textContent.getCancel());
        }
        viewById.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
            }
        });

        tv_cancle_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPopupWindow.dismiss();
            }
        });

        String string = PreferenceUtil.getString("language", "");
        String langstr = "";
        if (string.contains("zh")){
            langstr = "zh-cn";
        }else if (string.equals("ja")){
            langstr = "japan";
        }else{
            langstr = "en";
        }
        final String strinfo = langstr;
        MyLog.e("语言环境",string+"    语言环境");

        llfacebook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ShareLinkContent linkContent = new ShareLinkContent.Builder()
                        .setContentUrl(Uri.parse(domain + urlstr + "id=" + goodsid+"&lang="+strinfo))
                        .setContentTitle(store_name)
                        .setContentDescription(store_info)
                        .setImageUrl(Uri.parse(imagebig))
                        .build();
                shareDialog.show(linkContent);
                mPopupWindow.dismiss();
            }
        });
        llwx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                shopid=shopid + "&version="+m.getVersion();
                String appid = getString(R.string.weixin_appid);
//                String url = "https://www.seeland-wood.com/index/material/detail?id=13614";
                String url = domain + urlstr + "id=" + goodsid+"&lang="+strinfo;
                String title = store_name;
                String description = store_name;
//                String description = store_info;
//                String url = "zyt://app/openwith?id=20181015";
                Log.e("分享链接", url + "   链接");
                Log.e("分享链接title", title + "   链接");
                Log.e("分享链接description", description + "   链接");
                ShareUtil.shareToweixin(GoodsInfomationActivity.this, url, title, description, bitmap, appid);
                mPopupWindow.dismiss();
            }
        });
        llwxp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String appid = getString(R.string.weixin_appid);
                String url = domain + urlstr + "id=" + goodsid+"&lang="+strinfo;
                String title = store_name;
                String description = store_info;
                ShareUtil.shareToweixinp(GoodsInfomationActivity.this, url, title, description, bitmap, appid);
                mPopupWindow.dismiss();
            }
        });

//        int mScreenWidth = getWindowManager().getDefaultDisplay().getWidth();
//        int mScreenheightth = getWindowManager().getDefaultDisplay().getHeight();
//        mPopupWindow = new PopupWindow(popupWindow, mScreenWidth, mScreenheightth);

//        DisplayMetrics dm = new DisplayMetrics();
//        getWindowManager().getDefaultDisplay().getMetrics(dm);
//        mPopupWindow = new PopupWindow(dm.widthPixels, dm.heightPixels);

        mPopupWindow = new PopupWindow(popupWindow, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT);
        int mPopupWindowWidth = mPopupWindow.getWidth();
        int mPopupWindowHeight = mPopupWindow.getHeight();
        // 需要设置一下此参数，点击外边可消失
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setFocusable(true); // pop 显示时， 不让外部 view 响应点击事件
        //防止被底部虚拟键挡住
        mPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        if (Build.VERSION.SDK_INT >= 24) { // Android 7.x中,PopupWindow高度为match_parent时,会出现兼容性问题,需要处理兼容性
 //           int offsetY = DensityUtil.dip2px(context, utils.getNavigationBarHeight(context));
//            if (Build.VERSION.SDK_INT >= 25) { // Android 7.1中，PopupWindow高度为 match_parent 时，会占据整个屏幕
//                //故而需要在 Android 7.1上再做特殊处理
//                int screenHeight = heightPixels; // 获取屏幕高度
////                int screenHeight = DisplayUtil.getScreenHeight(MainActivity.this); // 获取屏幕高度
//                mPopupWindow.setHeight(screenHeight - utils.getNavigationBarHeight(context)); // 重新设置 PopupWindow 的高度
//            }
            int Screenheightth = getWindowManager().getDefaultDisplay().getHeight();
            //utils.getNavigationBarHeight(context);
            mPopupWindow.showAtLocation(img_collect,
                    Gravity.BOTTOM,
                    0,
                    Screenheightth/2 );
            MyLog.e("底部导航栏高度", utils.getNavigationBarHeight(context) + "    gaodu");

//            mPopupWindow.showAtLocation(img_collect, Gravity.NO_GRAVITY, 0, offsetY);
        } else {
//            mPopupWindow.showAsDropDown(img_collect);
            int Screenheightth = getWindowManager().getDefaultDisplay().getHeight();
            //utils.getNavigationBarHeight(context);
            mPopupWindow.showAtLocation(img_collect,
                    Gravity.BOTTOM,
                    0,
                    0 );
        }
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });

    }

    private void showBigImage(String url) {
        LayoutInflater layoutInflater = LayoutInflater.from(context);
        View popupWindow = layoutInflater.inflate(R.layout.popup_bigimage, null);
        ZoomImageview iv_zoom = popupWindow.findViewById(R.id.iv_zoom);
        ImageView img_close = popupWindow.findViewById(R.id.img_close);
        img_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mPopupWindow != null) {
                    mPopupWindow.dismiss();
                }
            }
        });
        Glide.with(this).load(url).into(iv_zoom);

        int mScreenWidth = getWindowManager().getDefaultDisplay().getWidth();
        mPopupWindow = new PopupWindow(popupWindow, ActionBar.LayoutParams.MATCH_PARENT,
                ActionBar.LayoutParams.MATCH_PARENT);
        mScreenWidth = getWindowManager().getDefaultDisplay().getHeight();
        int mPopupWindowWidth = mPopupWindow.getWidth();
        int mPopupWindowHeight = mPopupWindow.getHeight();
        // 需要设置一下此参数，点击外边可消失
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setFocusable(true); // pop 显示时， 不让外部 view 响应点击事件
        //防止被底部虚拟键挡住
        mPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        if (Build.VERSION.SDK_INT >= 24) { // Android 7.x中,PopupWindow高度为match_parent时,会出现兼容性问题,需要处理兼容性
            int offsetY = DensityUtil.dip2px(context, utils.getNavigationBarHeight(context));
            if (Build.VERSION.SDK_INT >= 25) { // Android 7.1中，PopupWindow高度为 match_parent 时，会占据整个屏幕
                //故而需要在 Android 7.1上再做特殊处理
                int screenHeight = heightPixels; // 获取屏幕高度
//                int screenHeight = DisplayUtil.getScreenHeight(MainActivity.this); // 获取屏幕高度
                // 设置SelectPicPopupWindow弹出窗体的高
                mPopupWindow.setHeight(screenHeight); // 重新设置 PopupWindow 的高度
//                mPopupWindow.setHeight(screenHeight - utils.getNavigationBarHeight(context)); // 重新设置 PopupWindow 的高度
            }
            mPopupWindow.showAtLocation(img_collect,
                    Gravity.BOTTOM,
                    0,
                    0);
            MyLog.e("底部导航栏高度", utils.getNavigationBarHeight(context) + "    gaodu");

        } else {
            mPopupWindow.showAtLocation(img_collect,
                    Gravity.BOTTOM,
                    0,
                    0);
//            mPopupWindow.showAsDropDown(img_collect);
        }

        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });

    }

    Bitmap bitmap = null;

    public void returnBitMap(final String url) {

        new Thread(new Runnable() {
            @Override
            public void run() {

                URL myFileUrl = null;

                try {
                    myFileUrl = new URL(url);
                } catch (MalformedURLException e) {
                    return;
                }
                HttpURLConnection conn = null;
                try {
                    conn = (HttpURLConnection) myFileUrl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    int responseCode = conn.getResponseCode();
                    if (responseCode == 200) {
                        InputStream is = conn.getInputStream();
                        conn.setReadTimeout(3000);
                        conn.setConnectTimeout(3000);
                        bitmap = BitmapFactory.decodeStream(is);
                        is.close();
                        conn.disconnect();
                        int width = bitmap.getWidth();
                        int height = bitmap.getHeight();
                        int newWidth = 100;
                        int newHeight = 100;
                        float scaleWidth = ((float) newWidth) / width;
                        float scaleHeight = ((float) newHeight) / height;
                        Matrix matrix = new Matrix();
                        matrix.postScale(scaleWidth, scaleHeight);
                        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (conn != null) {
                        conn.disconnect();
                    }
                }
            }
        }).start();
    }

    protected void hideBottomUIMenu() {
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
